package netty;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author : 李红磊
 * @version :1.0
 * @date : 2021/10/10 9:34
 * @description : BIO模型
 */
public class BioServer {


    public static void main(String[] args) throws IOException {


        ServerSocket serverSocket = new ServerSocket(6666);
        ExecutorService threadPool = Executors.newCachedThreadPool();
        System.out.println("服务端已启动");

        while (true) {

            final Socket socket = serverSocket.accept();//监听，等待客户端连接

            System.out.println("服务端连接到客户端");

            //连接到一个客户端，就创建一个线程.
            threadPool.execute(() ->handler(socket));


        }

    }

    //编写一个方法和客户端进行通讯
    public static void handler(Socket serverSocket) {

        byte[] bytes = new byte[1024];
        //通过socket获取输入流，读取管道中从客户端传来的数据
        try {
            InputStream inputStream = serverSocket.getInputStream();

            //循环读取数据
            while (true) {
                int read = inputStream.read();
                if (read != -1) {
                    System.out.println(new String(bytes,0,read));
                } else {
                    break;
                }



            }

        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}
